package com.bringspring.system.base.util;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.bringspring.common.database.source.DbBase;
import com.bringspring.common.database.util.ConnUtil;
import com.bringspring.common.database.model.DataSourceModel;
import com.bringspring.common.database.util.DbTypeUtil;
import com.bringspring.common.util.StringUtils;
import com.bringspring.common.util.context.SpringContext;

/**
 * @author 开发平台组
 * @version V1.0.0
 * @copyright 股份有限公司
 * @date 2021/3/12 15:31
 */
public class SourceUtil {

    public static DataSourceConfig dbConfig(String dbName, DataSourceModel linkEntity) {
        if (linkEntity == null) {
            linkEntity = SpringContext.getBean(DataSourceModel.class);
            if (StringUtils.isNotEmpty(dbName)) {
                linkEntity.setDbName(dbName);
            }
        }
        DataSourceConfig dsc = new DataSourceConfig();
        try {
            DbBase dbBase = DbTypeUtil.getDb(linkEntity);
            dsc.setDbType(dbBase.getMpDbType());
            dsc.setDriverName(dbBase.getDriver());
            dsc.setUsername(linkEntity.getUserName());
            dsc.setPassword(linkEntity.getPassword());
            dsc.setSchemaName(linkEntity.getDbSchema());

            // oracle 默认 schema = username
            if (dbBase.getMpDbType().toString().equalsIgnoreCase(DbType.ORACLE.getDb())) {
                dsc.setSchemaName(linkEntity.getUserName());
            }

            dsc.setUrl(ConnUtil.getUrl(linkEntity));
        } catch (Exception e) {
            e.getStackTrace();
        }
        return dsc;
    }

}
